<?php
/**
 * Created by PhpStorm.
 * User: xutao
 * Date: 2018/8/2
 * Time: 9:40
 */
namespace app\index\controller;
use app\common\model\LookModel;
use think\Loader;
use think\Session;

class Api extends Base {

    //清除session
    public function del_session(){
        Session::clear();
    }

    //见闻添加
    public function look_add(){
        if(\request()->isPost()){
            if(!Session::get('member')) return json(['code'=>9,'data'=>'','msg'=>'请登录']);
            $id = Session::get('member')['id'];
            $data = input();
            $data['member_id'] = $id;
            //验证
            $vaildate = Loader::validate('LookValidate');
            if(!$vaildate->check($data)) return json(['code'=>2,'data'=>'','msg'=>$vaildate->getError()]);
            $re = LookModel::create_data($data);
            if($re){
                return json(['code'=>200,'data'=>['look_id'=>$re],'msg'=>'添加成功']);
            }else{
                return json(['code'=>0,'data'=>'','msg'=>'添加失败']);
            }
        }else{
            return json(['code'=>0,'data'=>'','msg'=>'非法请求']);
        }
    }
    //全部见闻列表
    public function get_look_all(){
        if(\request()->isPost()){
            $count =  LookModel::where('state',1)->count();
            $page = input('page')?input('page'):1;
            $start = $page == 1?0:($page-1)*10;

            $data = LookModel::alias('l')->join('think_member m','m.id = l.member_id')->where('l.state',1)->order('l.create_time desc')->field('l.*,m.nickname')->limit($start,10)->select();
            return \json(['code'=>200,'data'=>$data,'count'=>$count,'msg'=>$start]);
        }else{
            return \json(['code'=>0,'data'=>'','msg'=>'非法请求']);
        }
    }
    //单图片上传
    public function upone_img(){
        $file = request()->file('file');
        // 移动到框架应用根目录/public/uploads/ 目录下
        if($file){
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            if($info){
                // 成功上传后 获取上传信息
               $src = 'public' . DS . 'uploads'.DS.$info->getSaveName();
               return json(['code'=>200,'data'=>['src'=>$src],'msg'=>'上传成功']);
            }else{
                // 上传失败获取错误信息
                return json(['code'=>0,'data'=>'','msg'=>$file->getError()]);
            }
        }else{
            return json(['code'=>0,'data'=>'','msg'=>'图片为空']);
        }
    }
}